package com.caipin.utils;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2020-01-16 15:45
 * @Description: 基于 POI 将数据导出到 excel
 */
public class ExportExcel {

    /**
     * 导出Excel工作簿
     *
     * @param sheetName 工作簿中的一张工作表的名称
     * @param titleName 表格的标题名称
     * @param headers   表格每一列的列名
     * @param dataSet   要导出的数据源
     * @param resultUrl 导出的excel文件地址
     * @param pattern   时间类型数据的格式
     */
    public static void exportExcel(String sheetName, String titleName, String[] headers, Collection<?> dataSet, String resultUrl, String pattern) {
        doExportExcel(sheetName, titleName, headers, dataSet, resultUrl, pattern);
    }


    private static void doExportExcel(String sheetName, String titleName, String[] headers, Collection<?> dataSet, String resultUrl, String pattern) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个工作表
        HSSFSheet sheet = workbook.createSheet(sheetName);
        // 设置工作表默认列宽度为20个字节
        sheet.setDefaultColumnWidth((short) 20);
        //在工作表中合并首行并居中
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1));

        HSSFCellStyle titleStyle = createTitleStyle(workbook);
        HSSFCellStyle headerStyle = createHeaderStyle(workbook);
        HSSFCellStyle dataStyle = createDataStyle(workbook);


        //创建标题行-增加样式-赋值
        HSSFRow titleRow = sheet.createRow(0);
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellStyle(titleStyle);
        titleCell.setCellValue(titleName);

        // 创建列首-增加样式-赋值
        HSSFRow row = sheet.createRow(1);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(headerStyle);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        fillCellData(dataSet, pattern, sheet, dataStyle);

        File file = new File(resultUrl);
        FileOutputStream outputStream = null;
        try {
            file.createNewFile();
            outputStream = FileUtils.openOutputStream(file);
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static void fillCellData(Collection<?> dataSet, String pattern, HSSFSheet sheet, HSSFCellStyle dataStyle) {
        HSSFRow row;// 创建表中数据行-增加样式-赋值
        Iterator<?> it = dataSet.iterator();
        int index = 1;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            Object t = it.next();
            // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            for (short i = 0; i < fields.length; i++) {

                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(dataStyle);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                try {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    Object value = getMethod.invoke(t, new Object[]{});
                    if (value == null) {
                        value = "";
                    }

                    // 如果是时间类型,按照格式转换
                    String textValue = null;
                    if (value instanceof Date) {
                        Date date = (Date) value;
                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                        textValue = sdf.format(date);
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        textValue = value.toString();
                    }

                    // 利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null) {
                        Pattern p = Pattern.compile("^\\d+(\\.\\d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            // 不是数字做普通处理
                            cell.setCellValue(textValue);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static HSSFCellStyle createDataStyle(HSSFWorkbook workbook) {
        // 创建[表中数据]样式
        HSSFCellStyle dataSetStyle = workbook.createCellStyle();
        setCellStyle(workbook, dataSetStyle, IndexedColors.GOLD, Font.COLOR_NORMAL, (short) 11);
        return dataSetStyle;
    }

    private static HSSFCellStyle createHeaderStyle(HSSFWorkbook workbook) {
        // 创建[列首]样式
        HSSFCellStyle headersStyle = workbook.createCellStyle();
        // 设置[列首]样式
        setCellStyle(workbook, headersStyle, IndexedColors.LIGHT_ORANGE, IndexedColors.VIOLET.index, (short) 12);
        return headersStyle;
    }

    /**
     * 设置标题样式
     *
     * @param workbook 工作簿
     */
    private static HSSFCellStyle createTitleStyle(HSSFWorkbook workbook) {
        // 创建[标题]样式
        HSSFCellStyle titleStyle = workbook.createCellStyle();
        // 设置[标题]样式
        setCellStyle(workbook, titleStyle, IndexedColors.LIGHT_BLUE, Font.COLOR_NORMAL, (short) 24);
        return titleStyle;
    }

    private static void setCellStyle(HSSFWorkbook workbook, HSSFCellStyle cellStyle, IndexedColors lightOrange, short color, short i) {
        cellStyle.setFillForegroundColor(lightOrange.index);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //创建[列首]字体
        HSSFFont headersFont = workbook.createFont();
        //设置[列首]字体
        headersFont.setColor(color);
        headersFont.setFontHeightInPoints(i);
        headersFont.setBold(true);
        // 把[列首字体]应用到[列首样式]
        cellStyle.setFont(headersFont);
    }


}
